package com.hzit.manager.config;

import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlCleaner;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.web.domain.AjaxResult;
import lombok.SneakyThrows;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactivePubSubCommands;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Configuration
public class HzitWebCallbackHandler {
    // 定制熔断、降级、限流异常信息
    @PostConstruct
    public void init(){
        // WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
        //     @Override
        //     public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        //         response.setContentType("application/json;charset=utf8");
        //         AjaxResult error = AjaxResult.error(HttpStatus.ERROR, "出现了限流错误！");
        //         response.getWriter().println(JSON.toJSONString(error));
        //         response.getWriter().flush();
        //     }
        // });

    }
    @Bean
    public BlockExceptionHandler sentinelBlockExceptionHandler() {
        return (request, response, e) -> {
            // 429 Too Many Requests
            response.setContentType("application/json;charset=utf8");
            response.setStatus(429);
            AjaxResult error = AjaxResult.error(HttpStatus.ERROR, "出现了限流错误！");
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(error));
            out.flush();
            out.close();
        };
    }
    @Bean
    public FilterRegistrationBean sentinelFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CommonFilter());
        registration.addUrlPatterns("/*");
        registration.setName("sentinelFilter");
        registration.setOrder(1);

        return registration;
    }
}
